package com.kpmg.datalake.operatelog.aspect;

import com.kpmg.datalake.operatelog.model.OperateLog;
import com.kpmg.datalake.operatelog.service.HandleLog;
import com.kpmg.datalake.operatelog.utils.IpUtils;
import eu.bitwalker.useragentutils.UserAgent;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author Alex.zhao [alex.zhao@kpmg.com]
 * @since Created on azhao6 on 2018-08-07 23:22:31
 * 操作日志拦截器
 */
@Aspect
public class OperateLogAspect {

    @Resource
    private HandleLog handleLog;

    @Around("@annotation(com.kpmg.datalake.operatelog.annotation.OptLog)")
    public Object operateLogAround(ProceedingJoinPoint pjp) throws Throwable {
        long operationTime = System.currentTimeMillis();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        UserAgent userAgent = null;
        OperateLog operateLog = new OperateLog();
        if (request != null) {
            operateLog.setIp(IpUtils.getIpAddress(request));
            operateLog.setUserName((String) request.getSession().getAttribute("userName"));
            userAgent = UserAgent.parseUserAgentString(request.getHeader("User-agent"));
        }
        Object result = null;
        //是否有错
        boolean isError = false;
        //错误堆栈错误
        Throwable stackLog = null;
        try {
            result = pjp.proceed();
        } catch (Throwable throwable) {
            isError = true;
            stackLog = throwable;
            throw throwable;
        } finally {
            if (StringUtils.isBlank(operateLog.getUserName()) && request != null) {
                operateLog.setUserName((String) request.getSession().getAttribute("userName"));
            }
            operateLog.setRequestStatus(isError ? 1 : 0);
            operateLog.setBeginTime(new Date(operationTime));
            handleLog.doHandlerLog(pjp, stackLog, result, userAgent, operateLog,RequestContextHolder.getRequestAttributes());
        }

        return result;
    }
  }
